package com.codepilot.server.controller;

import com.codepilot.server.model.dto.UserDTO;
import com.codepilot.server.model.entity.Favor;
import com.codepilot.server.model.vo.CommonResult;
import com.codepilot.server.service.FavorService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = {"题目收藏夹"})
@RestController
@RequestMapping("/api/favor")
public class FavorController {
    @Autowired
    private FavorService favorService;

    @GetMapping
    public CommonResult<List<Favor>> getFavorList(@RequestHeader("Authorization") String token) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        return CommonResult.success(favorService.getFavorList(userId));
    }
    @PostMapping
    public CommonResult<Integer> createFavor(@RequestHeader("Authorization") String token, @RequestBody Favor favor) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        favor.setUserId(userId);
        return CommonResult.success(favorService.createFavor(favor));
    }
    @PutMapping
    public CommonResult<Integer> updateFavor(@RequestHeader("Authorization") String token, @RequestBody Favor favor) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        favor.setUserId(userId);
        return CommonResult.success(favorService.updateFavor(favor));
    }
    @DeleteMapping("/{problemUid}")
    public CommonResult<Integer> deleteFavor(@RequestHeader("Authorization") String token, @PathVariable("problemUid") int problemUid) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        return CommonResult.success(favorService.deleteFavor(userId, problemUid));
    }
}